/**
 *
 *
 *
 *
 *
 */

package com.simple.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dfe.modules.sys.dao.SysUserRoleDao;
import com.dfe.modules.sys.entity.SysUserRoleEntity;
import com.dfe.modules.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户与角色对应关系
 *
 *
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

	@Override
	public void saveOrUpdate(Long userId, List<Integer> roleIdList) {
		//先删除用户与角色关系
		Map<String,Object> param = new HashMap<>();
		param.put("user_id", userId);
		removeByMap(param);

		if(roleIdList == null || roleIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Integer roleId : roleIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);

			save(sysUserRoleEntity);
		}
	}

	@Override
	public List<Integer> queryRoleIdList(Long userId) {
		return baseMapper.queryRoleIdList(userId);
	}


	@Override
	public Boolean checkIsAdmin(Long userId) {
		//1,4,5
		List<SysUserRoleEntity> userRoleList = list(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));
		for (SysUserRoleEntity access : userRoleList){
			if (1 == access.getRoleId() || 4 == access.getRoleId() || 5 == access.getRoleId()){
				return true;
			}
		}
		return false;
	}

	@Override
	public List<SysUserRoleEntity> getByUserId(Long userId) {
		return list(new QueryWrapper<SysUserRoleEntity>().eq("user_id",userId));
	}

	@Override
	public void deleteByRoleIdList(List<Integer> roleIds) {
		QueryWrapper<SysUserRoleEntity> qw = new QueryWrapper<SysUserRoleEntity>()
				.in(roleIds != null && !roleIds.isEmpty(),"role_id",roleIds);
		remove(qw);
	}
}
